package com.xk857.school.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xk857.config.AuthUtil;
import com.xk857.entities.Card;
import com.xk857.entities.CardDetail;
import com.xk857.entities.SysUser;
import com.xk857.feign.IFeignSystemController;
import com.xk857.school.mapper.CardDetailMapper;
import com.xk857.school.mapper.CardMapper;
import com.xk857.school.req.AddCardREQ;
import com.xk857.school.req.CardREQ;
import com.xk857.school.service.IMyCardService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xk857.util.base.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author CV大魔王
 * @since 2021-05-02
 */
@Service
@Primary
public class MyCardServiceImpl extends ServiceImpl<CardMapper, Card> implements IMyCardService {

    @Autowired
    private IFeignSystemController feignSystemController;

    @Autowired
    private CardDetailMapper cardDetailMapper;

    @Override
    public IPage<Card> queryPage(CardREQ req) {
        QueryWrapper<Card> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(req.getNickName())) {
            wrapper.like("nick_name", req.getNickName());
        }
        if (StringUtils.isNotEmpty(req.getSchoolName())) {
            wrapper.like("school_name", req.getSchoolName());
        }
        if (StringUtils.isNotEmpty(req.getPeopleName())) {
            wrapper.like("people_name", req.getPeopleName());
        }
        if (StringUtils.isNotEmpty(req.getMeId())) {
            wrapper.like("me_id", req.getMeId());
        }
        if (StringUtils.isNotEmpty(req.getStatus())) {
            wrapper.eq("status", req.getStatus());
        }else {
            wrapper.ne("status", "0");
        }
        if (StringUtils.isNotEmpty(req.getCardNum())) {
            wrapper.eq("card_num", req.getCardNum());
        }
        wrapper.orderByDesc("update_time");
        return baseMapper.selectPage(req.getPage(), wrapper);
    }

    @Override
    public Integer queryCount(String status) {
        QueryWrapper<Card> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(status)) {
            wrapper.like("status", status);
        }
        return baseMapper.selectCount(wrapper);
    }


    @Override
    public Result add(AddCardREQ req) {
        SysUser userInfo = AuthUtil.getUserInfo();

        boolean flag = false;
        Card card = new Card();
        card.setCreateTime(new Date());
        card.setCardNum(req.getCardNum());
        card.setSchoolName(req.getSchoolName());
        card.setRemark(req.getRemark());
        card.setPhone(req.getPhone());


        // 如果捡卡人id不为空，则代表是捡卡，获取捡卡用户的基本信息
        SysUser cardUser = null;
        if (StringUtils.isNotEmpty(req.getStatus())){
            SysUser sysUser = feignSystemController.findUserByUserId(userInfo.getId());
            // 发布人id
            card.setMeId(userInfo.getId());
            // 捡卡
            if (req.getStatus().equals("1")) {
                card.setUserId(userInfo.getId());
                card.setNickName(sysUser.getNickName());
                card.setUserImg(sysUser.getImageUrl());
                card.setStatus("1");
                // 查询用户信息是否有卡号相同的
                cardUser = feignSystemController.findUserByUserCard(req.getCardNum());
                // 如果不为空则代表找到卡主人,并存放到中间表通知卡主人
                if (cardUser!=null) {
                    flag = true;
                }
            }
            //丢卡
            if (req.getStatus().equals("3")) {
                card.setPeopleId(userInfo.getId());
                card.setPeopleName(sysUser.getNickName());
                card.setPeopleImg(sysUser.getImageUrl());
                card.setStatus("3");
            }
        }

        baseMapper.insert(card);
        if (flag){
            CardDetail cardDetail = new CardDetail();
            cardDetail.setUserId(cardUser.getId());
            cardDetail.setStatus("1");
            cardDetail.setCardUserId(card.getId());
            cardDetailMapper.insert(cardDetail);
            return Result.ok("找到丢卡用户，已通知该用户");
        }
        return Result.ok("信息发布成功");
    }

    @Override
    public Result getSchoolNameList() {
        QueryWrapper<Card> wrapper = new QueryWrapper<>();
        wrapper.groupBy("school_name");
        List<Card> cardList = baseMapper.selectList(wrapper);
        List<String> schoolList = new ArrayList<>();
        for (Card card : cardList) {
            schoolList.add(card.getSchoolName());
        }
        return Result.ok(schoolList);
    }

    @Override
    public Result update(Card req) {
        req.setUpdateTime(new Date());
        baseMapper.updateById(req);
        return Result.ok("更新成功");
    }

    @Override
    public Result delete(String id) {
        Card card = baseMapper.selectById(id);
        card.setStatus("0");
        baseMapper.updateById(card);
        return Result.ok("删除成功");
    }

    @Override
    public Integer queryCountMonth() {
        return baseMapper.queryCountMonth();
    }

    @Override
    public Integer queryCountFirstMonth() {
        return baseMapper.queryCountFirstMonth();
    }

    @Override
    public Integer queryCountWeek() {
        return baseMapper.queryCountWeek();
    }

    @Override
    public Integer queryCountFirstWeek() {
        return baseMapper.queryCountFirstWeek();
    }

    @Override
    public Result updateComplete(String cardId) {
        Card card = baseMapper.selectById(cardId);
        card.setStatus("2");

        SysUser userInfo = AuthUtil.getUserInfo();
        SysUser user = feignSystemController.findUserByUserId(userInfo.getId());

        if (user.getId().equals(card.getUserId())) {
            return Result.error("您不能操作自己发布的信息");
        }
        card.setPeopleId(user.getId());
        card.setPeopleName(user.getUsername());
        card.setPeopleImg(user.getImageUrl());

        baseMapper.updateById(card);
        return Result.ok();
    }

    // 捡到校园卡
    @Override
    public Result updatePickUp(String cardId) {
        Card card = baseMapper.selectById(cardId);
        card.setStatus("2");

        SysUser userInfo = AuthUtil.getUserInfo();
        SysUser user = feignSystemController.findUserByUserId(userInfo.getId());

        if (user.getId().equals(card.getPeopleId())) {
            return Result.error("您不能操作自己发布的信息");
        }

        card.setUserId(user.getId());
        card.setNickName(user.getUsername());
        card.setUserImg(user.getImageUrl());

        baseMapper.updateById(card);
        return Result.ok("修改成功");
    }
}
